package com.zyx.juc.cf.my;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yaxi.Zhang
 * @since 2022/6/13 11:25
 */
public class CompletableFutureAnyOfDemo {
    private static final AtomicInteger result = new AtomicInteger(0);
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture[] futures = new CompletableFuture[10];

        for (int i = 0; i < 10; i++) {
            CompletableFuture<Void> myFuture = CompletableFuture.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000 + ThreadLocalRandom.current().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    result.getAndIncrement();
                }
            });

            futures[i] = myFuture;
        }

        CompletableFuture myfuture = CompletableFuture.anyOf(futures).thenRun(() -> System.out.println(result));

        myfuture.get();
    }
}
